/**
 * @Title: PmCaptcha
 * @Package cn.com.artemis.framework.service.captcha.utils
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-胥钰淋
 * @date 2016/11/7 16:48
 * @version V1.0
 */
package cn.com.yiqi.wsc.service.captcha.utils;

import cn.com.artemis.common.util.date.PaxDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Random;

/**
 *
 *@ClassName: PmCaptcha
 * @Description: TODO
 * @author 会员系统组-胥钰淋
 * @date 2016/11/7 16:48
 *
 */
@Service
public class PmCaptcha {

    private static final int WIDTH = 85;
    private static final int HEIGHT = 20;
    private static final String[] strArr = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
    private String randomCodeKey;
    private int length = 4;

    public PmCaptcha (String randomCodeKey) {
        if (StringUtils.isEmpty(randomCodeKey)) {
            throw new IllegalArgumentException("randomCodeKey can not be blank");
        } else {
            this.randomCodeKey = randomCodeKey;
        }
    }

    public PmCaptcha (int length) {
        this.length = length;
    }

    public PmCaptcha () {
    }

    private String drawGraphic(BufferedImage image) {
        Graphics2D g = image.createGraphics();
        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, 85, 20);
        g.setFont(new Font("Times New Roman", 0, 18));
        g.setColor(getRandColor(160, 200));

        int i;
        for(int sRand = 0; sRand < 155; ++sRand) {
            i = random.nextInt(85);
            int rand = random.nextInt(20);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(i, rand, i + xl, rand + yl);
        }

        String var9 = "";

        for(i = 0; i < 4; ++i) {
            String var10 = String.valueOf(strArr[random.nextInt(strArr.length)]);
            var9 = var9 + var10;
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(var10, 13 * i + 6, 16);
        }

        g.dispose();
        return var9;
    }

    private String drawGraphic(BufferedImage image, int captchaSize) {
        if(captchaSize < 4) {
            throw new RuntimeException("验证码长度不能小于四位！！");
        } else {
            Graphics2D g = image.createGraphics();
            Random random = new Random();
            g.setColor(getRandColor(200, 250));
            g.fillRect(0, 0, 85, 20);
            g.setFont(new Font("Times New Roman", 0, 18));
            g.setColor(getRandColor(160, 200));

            int i;
            for(int sRand = 0; sRand < 155; ++sRand) {
                i = random.nextInt(85);
                int rand = random.nextInt(20);
                int xl = random.nextInt(12);
                int yl = random.nextInt(12);
                g.drawLine(i, rand, i + xl, rand + yl);
            }

            String var10 = "";

            for(i = 0; i < length; ++i) {
                String var11 = String.valueOf(strArr[random.nextInt(strArr.length)]);
                var10 = var10 + var11;
                g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
                g.drawString(var11, 13 * i + 6, 16);
            }

            g.dispose();
            return var10;
        }
    }

    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if(fc > 255) {
            fc = 255;
        }

        if(bc > 255) {
            bc = 255;
        }

        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static final String encrypt(String srcStr) {
        try {
            String e = "";
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(srcStr.getBytes("utf-8"));
            byte[] var7 = bytes;
            int var6 = bytes.length;

            for(int var5 = 0; var5 < var6; ++var5) {
                byte b = var7[var5];
                String hex = Integer.toHexString(b & 255).toUpperCase();
                e = e + (hex.length() == 1?"0":"") + hex;
            }

            return e;
        } catch (Exception var9) {
            throw new RuntimeException(var9);
        }
    }

    private static String getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Cookie[] var6 = cookies;
            int var5 = cookies.length;

            for(int var4 = 0; var4 < var5; ++var4) {
                Cookie cookie = var6[var4];
                if(cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static boolean validate(HttpServletRequest request, HttpServletResponse response, String inputRandomCode, String randomCodeKey) {
        if(StringUtils.isEmpty(inputRandomCode)) {
            return false;
        } else {
            try {
                inputRandomCode = encrypt(inputRandomCode);
                boolean var5 = inputRandomCode.equals(getCookie(request, randomCodeKey));
                return var5;
            } catch (Exception var9) {
                var9.printStackTrace();
            } finally {
                Cookie cookie = new Cookie(randomCodeKey, (String)null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }

            return false;
        }
    }

    public static boolean validate(HttpServletRequest request, String code) {
        if(StringUtils.isEmpty(code)) {
            return false;
        } else {
            Date s_date = (Date)request.getSession().getAttribute("KAPTCHA_SESSION_DATE");
            if(s_date != null && PaxDateUtil.addMin(2, s_date).before(new Date())) {
                request.getSession().removeAttribute("KAPTCHA_SESSION_KEY");
                request.getSession().removeAttribute("KAPTCHA_SESSION_DATE");
                return false;
            } else {
                String s_code = (String)request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
                request.getSession().removeAttribute("KAPTCHA_SESSION_KEY");
                request.getSession().removeAttribute("KAPTCHA_SESSION_DATE");
                if (StringUtils.isNotEmpty(s_code)) {
                    return s_code.equals(code);
                } else {
                    return false;
                }
            }
        }
    }

    /**
     * 获取验证码
     * @param request
     * @param response
     */
    public void getCaptcha (HttpServletRequest request, HttpServletResponse response) {
        BufferedImage image = new BufferedImage(85, 20, 1);
        String vCode = drawGraphic(image, length);
        request.getSession().setAttribute("KAPTCHA_SESSION_KEY", vCode);
        request.getSession().setAttribute("KAPTCHA_SESSION_DATE", new Date());
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);
        response.setContentType("image/jpeg");
        ServletOutputStream sos = null;

        try {
            sos = response.getOutputStream();
            ImageIO.write(image, "jpeg", sos);
        } catch (Exception var12) {
            throw new RuntimeException(var12);
        } finally {
            if(sos != null) {
                try {
                    sos.close();
                } catch (IOException var11) {
                    var11.printStackTrace();
                }
            }

        }
    }

}
